package com.blog.user.controller;


import com.blog.user.service.BlogService;
import com.blog.utils.JWTUtils;
import com.blog.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zw
 * @since 2022-02-21
 */
@RestController
@RequestMapping("/user")
@CrossOrigin("*")
public class BlogController {
//获取所有文章列表
    @Autowired
    BlogService blogService;
    @GetMapping("/blog/{page-size}/{limit}")
    public ResponseResult getAllBlog(
            @PathVariable("page-size") Integer pageSize,
            @PathVariable("limit") Integer limit,
            @RequestHeader("token") String token){
        if(!JWTUtils.checkToken(token)){
            return ResponseResult.error().message("用户登录信息过期,请重新登录");
        }
        Map<String, Object> blogs = blogService.getAllBlog(pageSize,limit);
        if(ObjectUtils.isEmpty(blogs))
            return ResponseResult.ok().message("未查到文章").data("blogCount",0);
        else
            return ResponseResult.ok().message("获取数据成功").data(blogs);
    }
    /**
     * 通过标题模糊查询所有文章
     * @param title
     * @param pageSize
     * @param limit
     * @param token
     * @return
     */
    @GetMapping("/getAllBlogByTitle/{title}/{page-size}/{limit}")
    public ResponseResult getAllBlogByTitle(
            @PathVariable("title") String title,
            @PathVariable("page-size") Integer pageSize,
            @PathVariable("limit") Integer limit,
            @RequestHeader("token") String token){
        if(!JWTUtils.checkToken(token)){
            return ResponseResult.error().message("用户登录信息过期,请重新登录");
        }
        Map<String, Object> blogs = blogService.getAllBlogByTitle(title,pageSize,limit);
        if(ObjectUtils.isEmpty(blogs))
            return ResponseResult.ok().message("未查到文章").data("blogCount",0);
        else
            return ResponseResult.ok().message("获取数据成功").data(blogs);
    }

    /**
     * 根据文章id删除文章
     * @param id
     * @return
     */
    @DeleteMapping("/deleteArticle/{userId}/{id}")
    public ResponseResult deleteArticle(@PathVariable("id") Integer id,
                                        @PathVariable String userId,
                                        @RequestHeader("token") String token){
        if(!JWTUtils.checkToken(token)){
            return ResponseResult.error().message("用户登录信息过期,请重新登录");
        }
        if(blogService.deleteArticle(userId,id))
            return ResponseResult.ok();
        else
            return ResponseResult.error();
    }
}

